from __future__ import division
from collections import defaultdict

classes = [0,1,2,3,4,5,6]

trainfile = 'train.txt'
benchmark = defaultdict(list)
trainingset = dict()
f = open(trainfile, 'r')
total = 0
for line in f:
    t = line.replace('\n','').split(' ')
    benchmark[int(t[1])].append(int(t[0]))
    trainingset[int(t[0])] = int(t[1])
    total += 1
benchmark = dict(benchmark)
f.close()

for c in classes:
    positive = []
    negative = []
    tp = []
    fp = []
    fn = []
    tn = []
    predictionfile = open('prediction%d.txt'%c, 'r')
    docid = 0
    for line in predictionfile:
        score = float(line.replace('\n',''))
        if score >= 0:
            positive.append(docid)
            cls = trainingset.get(docid,7)
            if cls == c:
                tp.append(docid)
            elif cls != 7:
                fp.append(docid)
        else:
            negative.append(docid)
            cls = trainingset.get(docid,7)
            if cls == c:
                fn.append(docid)
            elif cls != 7:
                tn.append(docid)
        docid += 1
    predictionfile.close()
            
    print '%-10d# class'%c
    print '%-10s# %% accuracy on training set'%('%.2f%%'%((len(tp)+len(tn))*100/total))
    print '%-10d# correct on training set'%(len(tp)+len(tn))
    print '%-10d# incorrect on training set'%(len(fp)+len(fn))
    print '%-10s# %% precision on training set'%('%.2f%%'%(len(tp)*100/(len(tp)+len(fp))))
    print '%-10s# %% recall on training set'%('%.2f%%'%(len(tp)*100/(len(tp)+len(fn))))
    print '%-10d# positive on collection'%(len(positive))
    print '%-10d# total on collection'%(len(positive)+len(negative))
    print

results = defaultdict(list)
for c in classes:
    docid = 0
    f = open('prediction%d.txt'%c,'r')
    for line in f:
        score = float(line.replace('\n',''))
        if score >= 0:
            results[docid].append(str(c))
        docid += 1
    f.close()

f = open('labSVM.txt','w')
for k in xrange(11951):
    f.write(' '.join(results[k])+'\n')
f.close()

    

















    